package com.sharemarking.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.sharemarking.system.dto.Page;
import com.sharemarking.system.dto.agreement.AgreementDto;
import com.sharemarking.system.dto.orgManagement.OrgVerifyInfoDto;
import com.sharemarking.system.dto.orgVerify.OrgVerifyListDto;
import com.sharemarking.system.mapper.AgreementMapper;
import com.sharemarking.system.mapper.OrgVerifyMapper;
import com.sharemarking.wa.common.entity.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author dxy
 */
@Controller
@RequestMapping("system/productWasteManagement")
public class ProductWasteManagementController {
    @Autowired
    private OrgVerifyMapper om;
    @Autowired
    private HttpSession session;
    @Autowired
    private AgreementMapper am;

    /**
     * 列表页面
     *
     * @param
     * @param model
     */
    @GetMapping("index")
    @PreAuthorize("hasPermission('base','all')")
    public String index(OrgVerifyListDto obj, Integer page, Model model, Integer isSession) {
        int size = 10;
        if (page == null) {
            page = 0;
        }
        // session 参数回显
        if (isSession != null) {
            // 如果isSession为1，代表要从session取条件参数，一般应用在某操作之后要保存查询参数
            obj = session.getAttribute("query") == null ? obj : (OrgVerifyListDto) session.getAttribute("query");
            size = session.getAttribute("size") == null ? size : (int) session.getAttribute("size");
            page = session.getAttribute("page") == null ? page : (int) session.getAttribute("page");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", page * size);
        map.put("pageSize", size);
        map.put("verify", 1);
        if (!StringUtils.isEmpty(obj.getMobile())) {
            map.put("mobile", obj.getMobile());
        }
        if (!StringUtils.isEmpty(obj.getOrgName())) {
            map.put("orgName", obj.getOrgName());
        }
        List<OrgVerifyListDto> list = om.getProductWasteOrgList(map);
        int total = om.getProductWasteOrgListTotal(map);
        model.addAttribute("page", new Page<>(page, size, total, list));
        model.addAttribute("query", obj);
        // session 参数保存
        session.setAttribute("query", obj);
        session.setAttribute("size", size);
        session.setAttribute("page", page);
        return "orgManagement/productWasteIndex";
    }


    /**
     * 新增、编辑页面
     *
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String get(@PathVariable("id") int id, Model model) {
        OrgVerifyInfoDto obj = new OrgVerifyInfoDto();
        if (id > 0) {
            obj = om.getInfo(id);
        } else {
            model.addAttribute("obj", obj);
            return "orgManagement/productWasteFormInsert";
        }
        List<String> attach = om.getAttachList(id);
        model.addAttribute("attach", attach);
        model.addAttribute("obj", obj);
        return "orgManagement/productWasteForm";
    }

    /**
     * 新增、编辑
     *
     * @param obj
     * @param model
     * @return
     */
    @PostMapping("{id}")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String post(OrgVerifyInfoDto obj, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) throws Exception {


        //企业认证转换
        OrgVerify orgVerify = new OrgVerify();
        BeanUtils.copyProperties(obj, orgVerify);

        //更新用户表
        Member member = new Member();
        member.setMobile(obj.getMobile());
        member.setRealName(obj.getMemberName());
        member.setNickName("手机尾号" + member.getMobile().substring(member.getMobile().length() - 4));
        member.setHeadImg("headImg/memberBigHead.png");
        //更新企业表
        Org org = new Org();
        org.setName(obj.getName());
        org.setRealName(obj.getName());

        if (obj.getId() == 0) {
            if (om.isBindMobile(obj.getMobile()) != 0) {
                redirectAttributes.addFlashAttribute("msg", "该手机号已经绑定其它单位！");
                return "redirect:" + obj.getId();
            }


            //插入用户
            member.setRole(0);//产废端
            member.setCreateDate(new Date());
            member.setPassword("96e79218965eb72c92a549dd5a330112");//默认密码111111
            member.setAlias(UUID.randomUUID().toString().replaceAll("-", ""));
            om.insertMember(member);

            //新插入企业
            org.setCreateDate(new Date());
            org.setMemberId(member.getId());
            om.insertOrg(org);

            //插入认证企业
            orgVerify.setOrgId(org.getId());
            orgVerify.setMemberId(member.getId());
            orgVerify.setExamState(1);//已通过
            orgVerify.setCreateDate(new Date());
            om.insert(orgVerify);

            //插入企业用户表
            om.insertOrgMember(org.getId(), member.getId());
        } else {
            Integer memberId = om.getMemberId(obj.getId());
            if (om.isBindMobileByMemberId(obj.getMobile(), memberId) != 1) {
                if (om.isBindMobile(obj.getMobile()) != 0) {
                    redirectAttributes.addFlashAttribute("msg", "该手机号已经绑定其它单位！");
                    return "redirect:" + obj.getId();
                }
            }

            //更新企业认证表
            orgVerify.setUpdateDate(new Date());
            om.updateById(orgVerify);

            //更新企业表
            org.setId(obj.getOrgId());
            om.updateOrg(org);

            //更新用户表
            member.setId(memberId);
            member.setUpdateDate(new Date());
            om.updateMember(member);
        }

        String attachStr= request.getParameter("attachStr");
        if (!StringUtils.isEmpty(attachStr)){
            String [] attachList = attachStr.split(",");
            for (String s : attachList){
                if (!StringUtils.isEmpty(s)){
                    OrgVerifyAttachment orgVerifyAttachment = new OrgVerifyAttachment();
                    orgVerifyAttachment.setAttachment(s);
                    orgVerifyAttachment.setType(0);
                    orgVerifyAttachment.setOrgVerifyId(orgVerify.getId());
                    orgVerifyAttachment.setCreateDate(new Date());
                    om.insertAttach(orgVerifyAttachment);
                }
            }
        }

        model.addAttribute("obj", obj);
        redirectAttributes.addFlashAttribute("msg", "操作成功!");
        return "redirect:index?isSession=1";
    }


    /**
     * 详情页面
     *
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("info/{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String getInfo(@PathVariable("id") int id, Model model) {
        OrgVerify obj = new OrgVerify();
        if (id > 0) {
            obj = om.selectById(id);
        } else {
            model.addAttribute("obj", obj);
        }
        List<String> attach = om.getAttachList(id);
        model.addAttribute("attach", attach);
        model.addAttribute("obj", obj);
        return "orgVerify/info";
    }

    /**
     * 审核
     *
     * @param obj
     * @param model
     * @return
     */
    @GetMapping("exam")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String exam(int id, int type, String rejectReason, Model model, RedirectAttributes redirectAttributes) {
        OrgVerify orgVerify = new OrgVerify();
        orgVerify.setExamState(type);
        if (type == 2) {
            if (StringUtils.isEmpty(rejectReason)) {
                redirectAttributes.addFlashAttribute("msg", "驳回理由不可为空！");
                return "redirect:index?isSession=1";
            }
            orgVerify.setRejectReason(rejectReason);
        } else {
            orgVerify.setRejectReason(null);
        }
        orgVerify.setId(id);
        orgVerify.setUpdateDate(new Date());
        om.updateById(orgVerify);
        redirectAttributes.addFlashAttribute("msg", "操作成功！");
        return "redirect:index?isSession=1";
    }


    /**
     * 协议列表页面
     *
     * @param
     * @param model
     */
    @GetMapping("agreement/{orgId}")
    @PreAuthorize("hasPermission('base','all')")
    public String agreementList(Agreement obj, String orgName, Integer page, Model model, Integer isSession) {
        int size = 10;
        if (page == null) {
            page = 0;
        }
        // session 参数回显
        if (isSession != null) {
            // 如果isSession为1，代表要从session取条件参数，一般应用在某操作之后要保存查询参数
            obj = session.getAttribute("query") == null ? obj : (Agreement) session.getAttribute("query");
            size = session.getAttribute("size") == null ? size : (int) session.getAttribute("size");
            page = session.getAttribute("page") == null ? page : (int) session.getAttribute("page");
        }
        Map<String, Object> map = new HashMap<>();
        map.put("pageIndex", page * size);
        map.put("pageSize", size);
        QueryWrapper<Agreement> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(obj.getName())) {
            queryWrapper.like("name", obj.getName());
        }
        if (!StringUtils.isEmpty(obj.getExamState())) {
            queryWrapper.eq("exam_state", obj.getExamState());
        }
        queryWrapper.eq("org_id", obj.getOrgId());
        List<Agreement> list = am.selectList(queryWrapper.last("limit " + page * size + "," + size));
        int total = am.selectCount(queryWrapper);
        for (Agreement a : list) {
            if (a.getPics() != null && a.getPics().split(",").length > 1) {
                a.setPics(a.getPics().split(",")[0]);
            }
            if (a.getPics() != null && a.getPics().equals("")) {
                a.setPics(null);
            }
        }
        model.addAttribute("page", new Page<>(page, size, total, list));
        model.addAttribute("query", obj);
        model.addAttribute("orgName", orgName);
        // session 参数保存
        session.setAttribute("query", obj);
        session.setAttribute("size", size);
        session.setAttribute("page", page);
        session.setAttribute("orgId", obj.getOrgId());
        session.setAttribute("orgName", orgName);
        return "orgManagement/agreementIndex";
    }


    @GetMapping("agreement/info/{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String agreementInfo(Agreement obj, String orgName, Integer orgId, Model model) throws UnsupportedEncodingException {
        if (obj.getId() > 0) {
            obj = am.selectById(obj.getId());
        } else {
            model.addAttribute("obj", obj);
        }
        if (obj.getPics() != null) {
            List<String> picStr = Arrays.asList(obj.getPics().split(","));
            model.addAttribute("picStr", picStr);
        }
        model.addAttribute("obj", obj);
        model.addAttribute("orgName", orgName);
        model.addAttribute("orgId", orgId);

        session.setAttribute("orgId", orgId);
        session.setAttribute("orgName", orgName);
        return "orgManagement/agreementForm";
    }

    @PostMapping("agreement/info/{id}")
    @PreAuthorize("hasPermission('base','all')")
    public String infoSubmit(AgreementDto agreementDto, @PathVariable("id") int id, Model model, RedirectAttributes redirectAttributes) throws ParseException, UnsupportedEncodingException {
        Agreement agreement = new Agreement();
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = simpleDateFormat.parse(agreementDto.getExpireDate());
        agreement.setName(agreementDto.getName());
        agreement.setPics(agreementDto.getPics());
        agreement.setExpireDate(date);
        agreement.setOrgId((Integer) session.getAttribute("orgId"));
        if (id == 0) {
            agreement.setCreateDate(new Date());
            agreement.setPics(agreementDto.getPics());
            am.insert(agreement);
        } else {
            if (agreement.getPics().trim().isEmpty()) {
                agreement.setPics(null);
            }
            agreement.setId(id);
            agreement.setUpdateDate(new Date());
            am.update(agreement);
        }

        redirectAttributes.addFlashAttribute("msg", "操作成功！");
        String orgName = String.valueOf(session.getAttribute("orgName"));
        orgName = java.net.URLEncoder.encode(orgName, "UTF-8");
        return "redirect:../../agreement/" + session.getAttribute("orgId") + "?orgName=" + orgName;

    }


    @PostMapping("agreement/delete")
    @PreAuthorize("hasPermission('base','all')")
    @ResponseBody
    @Transactional
    public Object delete(String id) throws ParseException, UnsupportedEncodingException {
        am.deleteById(id);
        Map<String, Object> params = new HashMap<>();
        params.put("code", 200);
        return params;
    }


    /**
     * 审核
     */
    @GetMapping("agreement/exam")
    @PreAuthorize("hasPermission('base','all')")
    @Transactional
    public String agreementExam(int id, int type, String rejectReason, Model model, RedirectAttributes redirectAttributes) throws UnsupportedEncodingException {
        Agreement agreement = new Agreement();
        agreement.setExamState(type);
        if (type == 2) {
            if (StringUtils.isEmpty(rejectReason)) {
                redirectAttributes.addFlashAttribute("msg", "驳回理由不可为空！");
                return "redirect:index?isSession=1";
            }
            agreement.setRejectReason(rejectReason);
        } else {
            agreement.setRejectReason(null);
        }
        agreement.setId(id);
        agreement.setUpdateDate(new Date());
        am.updateById(agreement);
        redirectAttributes.addFlashAttribute("msg", "操作成功！");
        String orgName = String.valueOf(session.getAttribute("orgName"));
        orgName = java.net.URLEncoder.encode(orgName, "UTF-8");
        return "redirect:" + session.getAttribute("orgId") + "?orgName=" + orgName + "&isSession=1";
    }
}
